package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * 2516. 每种字符至少取 K 个
 *
 * @author liw
 * @version 1.0
 * @date 2022/12/26 14:13
 */
public class TakeCharacters {

    public static void main(String[] args) {
        TakeCharacters test = new TakeCharacters();

        // 8
//        String str = "aabaaaacaabc";
//        int k = 2;

        // -1
        String str  = "a";
        int k = 1;

        int i = test.takeCharacters(str, k);
        System.out.println(i);
    }

    public int takeCharacters(String s, int k) {
        char[] chars = s.toCharArray();
        int[] arr = new int[3];
        for (char aChar : chars) {
            arr[aChar - 'a']++;
        }
        for (int i = 0; i < 3; i++) {
            arr[i] -= k;
            if (arr[i] < 0) {
                return -1;
            }
        }
        int st = 0;
        int length = s.length();
        int[] arr2 = new int[3];
        int max = 0;
        for (int i = 0; i < length; i++) {
            arr2[chars[i] - 'a']++;
            while (arr2[0] > arr[0] || arr2[1] > arr[1] || arr2[2] > arr[2] ) {
                arr2[chars[st++] - 'a']--;
            }
            max = Math.max(max, i - st + 1);
        }
        return length - max;
    }

}
